#include <REGX52.H>
#include "DS1302.h"

char Time[]={24,12,5,19,16,00};//年，月，日，时，分，秒
sbit SCLK=P3^6;
sbit IO=P3^4;
sbit CE=P3^5;
void Write_Clock(unsigned char command,unsigned char date)
{	
	unsigned char i=0;
	CE=0;
	SCLK=0;

	CE=1;
	for(i=0;i<8;i++)//读入命令操作
	{		
		SCLK=0;		
		IO=command&(0x01<<i);
		SCLK=1;
	}
	
	for(i=0;i<8;i++)//写入数据
	{
		SCLK=0;
		IO=date&(0x01<<i);
		SCLK=1;
	}
	SCLK=0;
	CE=0;

}
unsigned char Read_Clock(unsigned char command)
{	
	unsigned char date=0;
	unsigned char i=0;
	CE=0;
	SCLK=0;
	CE=1;

	for(i=0;i<8;i++)
	{		
		SCLK=0;		
		IO=command&(0x01<<i);
		SCLK=1;
	}
	
	//读取数据
	for(i=0;i<8;i++)
	{
		SCLK=0;
		if(IO)
		{
			date=date|(0x01<<i);
		}
		SCLK=1;
	}  
	IO=0;
	SCLK=0;

    CE=0;

	return date;
}

void Set_Time()
{
	Write_Clock(0x8e,0x00);//解除写入保护
    Write_Clock(second_w,Time[5]/10*16+Time[5]%10);
    Write_Clock(minutes_w,Time[4]/10*16+Time[4]%10);
	Write_Clock(hour_w,Time[3]/10*16+Time[3]%10);
    Write_Clock(date_w,Time[2]/10*16+Time[2]%10);
	Write_Clock(month_w,Time[1]/10*16+Time[1]%10);
	Write_Clock(year_w,Time[0]/10*16+Time[0]%10);
}
void Read_Time()
{
		Time[5]=Read_Clock(second_r)/16*10+Read_Clock(second_r)%16;//bcd码,相当于用16进制来表示二进制
		Time[4]=Read_Clock(minutes_r)/16*10+Read_Clock(minutes_r)%16;
		Time[3]=Read_Clock(hour_r)/16*10+Read_Clock(hour_r)%16;
    	Time[2]=Read_Clock(date_r)/16*10+Read_Clock(date_r)%16;
		Time[1]=Read_Clock(month_r)/16*10+Read_Clock(month_r)%16;
		Time[0]=Read_Clock(year_r)/16*10+Read_Clock(year_r)%16;
		LCD_ShowNum(1,1,Time[0],2);
		LCD_ShowNum(1,4,Time[1],2);
		LCD_ShowNum(1,7,Time[2],2); 
		LCD_ShowNum(2,1,Time[3],2);
		LCD_ShowNum(2,4,Time[4],2);
		LCD_ShowNum(2,7,Time[5],2);
}